﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.Text;
using System.IO;
using System.Windows.Media.Imaging;
using System.Threading;
using System.Windows.Controls.Primitives;
using System.Net.NetworkInformation;

namespace TripleTriad
{
    public partial class CreaMazzo : PhoneApplicationPage
    {
        private static string key = "user";

        //storage dell'applicazione
        private static IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;

        private int player2id;
        private string player2name;

        private List<string> idlist;
        private Carta[] cardslist;

        private List<Button> addbuttons; //tutti i bottoni add
        private List<Button> removebuttons; //tutti i bottoni remove
        private List<Button> disabledaddbuttons; //bottoni add disabilitati
        private List<Button> disabledremovebuttons; //bottoni remove disabilitati

        private System.Windows.Threading.DispatcherTimer dispatcherTimer;

        private Popup popup;
        private PopUpUserControl control;

        private Style containerStyle = Application.Current.Resources["MyCardCanvas"] as Style;
        private Style borderStyle = Application.Current.Resources["MyCardCardBorder"] as Style;
        private Style nameTextStyle = Application.Current.Resources["MyCardTextName"] as Style;
        private Style topTextStyle = Application.Current.Resources["MyCardTextTOP"] as Style;
        private Style bottomTextStyle = Application.Current.Resources["MyCardTextBOT"] as Style;
        private Style leftTextStyle = Application.Current.Resources["MyCardTextLEFT"] as Style;
        private Style rightTextStyle = Application.Current.Resources["MyCardTextRIGHT"] as Style;
        private Style levelTextStyle = Application.Current.Resources["MyCardTextLEVEL"] as Style;
        private Style priceTextStyle = Application.Current.Resources["MyCardTextPrice"] as Style;
        private Style quantityTextStyle = Application.Current.Resources["friendsG"] as Style;
        private Style addStyle = Application.Current.Resources["Add"] as Style;
        private Style removeStyle = Application.Current.Resources["Remove"] as Style;

        public CreaMazzo()
        {
            InitializeComponent();

            addbuttons = new List<Button>();
            removebuttons = new List<Button>();
            disabledaddbuttons = new List<Button>();
            disabledremovebuttons = new List<Button>();
            idlist = new List<string>();
            cardslist = new Carta[5];

            dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 5);

            popup = new Popup();
            popup.Height = 300;
            popup.Width = 400;
            popup.VerticalOffset = 100;
            control = new PopUpUserControl();
            popup.Child = control;

            if (NetworkInterface.GetIsNetworkAvailable())
            {
                Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/createDeck.php");
                HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                loginRequest.Method = "POST";
                loginRequest.ContentType = "application/x-www-form-urlencoded";
                loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackCreateDeck), loginRequest);
            }
            else
            {
                MessageBox.Show("Connection error, please retry later.");
            }
        }//costruttore

        private void ConfirmButton_Click(object sender, RoutedEventArgs e)
        {
            Button clicked = sender as Button;
            clicked.IsEnabled = false;
            foreach (Button b in removebuttons)
            {
                b.IsEnabled = false;
            }

            //prendo le 5 carte dal db
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/get5Cards.php");
                HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                loginRequest.Method = "POST";
                loginRequest.ContentType = "application/x-www-form-urlencoded";
                loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackGet5Cards), loginRequest);
            }
            else
            {
                MessageBox.Show("Connection error, please retry later.");
            }

            popup.IsOpen = true;
 
 
            control.leaveButton.Click += (s, args) =>
            {
                popup.IsOpen = false;

                appSettings.Remove("mydeck");


                //escodallacoda
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/leaveQueue.php");
                    HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                    loginRequest.Method = "POST";
                    loginRequest.ContentType = "application/x-www-form-urlencoded";
                    loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackLeaveQueue), loginRequest);
                }
                else
                {
                    MessageBox.Show("Connection error, please retry later.");
                }

                dispatcherTimer.Stop();

                foreach (Button b in removebuttons)
                {
                    if (!disabledremovebuttons.Contains(b))
                    {
                        b.IsEnabled = true;
                    }
                }

                clicked.IsEnabled = true;
                
            };


            //cerco un player che sta cercando un avversario
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/searchOpponent.php");
                HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                loginRequest.Method = "POST";
                loginRequest.ContentType = "application/x-www-form-urlencoded";
                loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackSearch), loginRequest);
            }
            else
            {
                MessageBox.Show("Connection error, please retry later.");
            }
        }

        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/getMatchWithPlayerId.php");
            HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
            loginRequest.Method = "POST";
            loginRequest.ContentType = "application/x-www-form-urlencoded";
            loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackGetMatchWithPlayerId), loginRequest);   
        }

        private void addButton_Tap(object sender, EventArgs e)
        {
            Button clicked = sender as Button;
            Canvas canvas = clicked.Tag as Canvas;
            var list = canvas.Children.ToArray();

            TextBlock quantityBlock = list[6] as TextBlock;
            string cardid = clicked.Name;
            idlist.Add(cardid);
            textBlockSelected.Text = "Cards selected: " + idlist.Count.ToString();

            int quantity = (Convert.ToInt32(quantityBlock.Text)) - 1;
            quantityBlock.Text = quantity.ToString();

            Button rem = list[8] as Button; //attivo bottone per rimuovere la carta
            rem.IsEnabled = true;
            if (disabledremovebuttons.Contains(rem))
            {
                disabledremovebuttons.Remove(rem);
            }

            if (quantity == 0) //se non ho più carte di questo tipo disabilito il bottone
            {
                clicked.IsEnabled = false;
                disabledaddbuttons.Add(clicked);
            }

            if (idlist.Count == 5) //se ho già 5 carte selezionate disabilito tutti i bottoni
            {
                ConfirmButton.IsEnabled = true;
                foreach (Button b in addbuttons)
                {
                    b.IsEnabled = false;
                }
            }

        }

        private void removeButton_Tap(object sender, EventArgs e)
        {
            Button clicked = sender as Button;
            Canvas canvas = clicked.Tag as Canvas;
            var list = canvas.Children.ToArray();

            TextBlock quantityBlock = list[6] as TextBlock;
            string cardid = clicked.Name;
            idlist.Remove(cardid);
            textBlockSelected.Text = "Cards selected: " + idlist.Count.ToString();

            int quantity = (Convert.ToInt32(quantityBlock.Text)) + 1;
            quantityBlock.Text = quantity.ToString();

            Button add = list[7] as Button; //abilito il bottone add
            add.IsEnabled = true;
            if (disabledaddbuttons.Contains(add))
            {
                disabledaddbuttons.Remove(add);
            }

            TextBlock textMax = list[9] as TextBlock;
            int maxquantity = Convert.ToInt32(textMax.Text);

            if (quantity == maxquantity) //non posso rimuovere carte se prima non ne ho aggiunte
            {
                clicked.IsEnabled = false;
                removebuttons.Add(clicked);
            }

            if (idlist.Count == 0) //se non ho carte non posso toglierne
            {
                Button b = list[8] as Button;
                b.IsEnabled = false;
            }
            else //riabilito i bottoni add giusti
            {
                foreach (Button b in addbuttons)
                {
                    if (!disabledaddbuttons.Contains(b))
                    {
                        b.IsEnabled = true;
                    }
                }
                ConfirmButton.IsEnabled = false;
            }
        }

        //CreateDeck

        private void GetRequestStreamCallbackCreateDeck(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&id=" + io.getId().ToString();
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackCreateDeck), myRequest);
        }//GetRequestStreamCallbackCreate

        private void GetResponsetStreamCallbackCreateDeck(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingCreateDeck(result));
            }
        }//GetResponsetStreamCallbackCreate

        private void ParsingCreateDeck(string result)
        {
            //controllo result
            if (result != "")//ho preferiti
            {
                //parsing e creo lista
                string[] ris = majorSplit(result);
                foreach (string record in ris)
                {
                    string[] dati = minorSplit(record);
                    string id = dati[0];
                    string name = dati[1];
                    string imageURL = dati[2];
                    string top = dati[3];
                    string bottom = dati[4];
                    string left = dati[5];
                    string right = dati[6];
                    string quantity = dati[7];

                    //creo tutti i canvas che mostrano le carte da selezionare
                    Canvas container = new Canvas();
                    container.Style = containerStyle;
                    var containerback = new ImageBrush();
                    Uri imageuricontainer = new Uri("img/buttonbg.png", UriKind.Relative);
                    containerback.ImageSource = new BitmapImage(imageuricontainer);
                    container.Background = containerback;

                    Border bord = new Border();
                    bord.Style = borderStyle;
                    var bordback = new ImageBrush();
                    Uri imageuribord = new Uri(imageURL, UriKind.Relative);
                    bordback.ImageSource = new BitmapImage(imageuribord);
                    bord.Background = bordback;

                    TextBlock nameText = new TextBlock();
                    nameText.Style = nameTextStyle;
                    nameText.Foreground = new SolidColorBrush(Colors.Black);
                    nameText.Text = name;

                    TextBlock topText = new TextBlock();
                    topText.Style = topTextStyle;
                    topText.Foreground = new SolidColorBrush(Colors.Black);
                    topText.Text = top;

                    TextBlock bottomText = new TextBlock();
                    bottomText.Style = bottomTextStyle;
                    bottomText.Foreground = new SolidColorBrush(Colors.Black);
                    bottomText.Text = bottom;

                    TextBlock leftText = new TextBlock();
                    leftText.Style = leftTextStyle;
                    leftText.Foreground = new SolidColorBrush(Colors.Black);
                    leftText.Text = left;

                    TextBlock rightText = new TextBlock();
                    rightText.Style = rightTextStyle;
                    rightText.Foreground = new SolidColorBrush(Colors.Black);
                    rightText.Text = right;

                    TextBlock quantityText = new TextBlock();
                    quantityText.Style = priceTextStyle;
                    quantityText.Foreground = new SolidColorBrush(Colors.Black);
                    quantityText.Text = quantity;

                    Button addButton = new Button();
                    addButton.Name = id;
                    addButton.Style = addStyle;
                    Canvas.SetLeft(addButton, 302);
                    Canvas.SetTop(addButton, 58);
                    addButton.Content = "Add";
                    addButton.Background = new SolidColorBrush(Color.FromArgb(255, 7, 90, 0));
                    addButton.Tap += new EventHandler<GestureEventArgs>(addButton_Tap);
                    addButton.Tag = container;
                    addbuttons.Add(addButton);

                    Button removeButton = new Button();
                    removeButton.Name = id;
                    removeButton.Style = addStyle;
                    Canvas.SetLeft(removeButton, 302);
                    Canvas.SetTop(removeButton, 118);
                    removeButton.Content = "Remove";
                    removeButton.Background = new SolidColorBrush(Color.FromArgb(255, 135, 0, 0));
                    removeButton.IsEnabled = false;
                    removeButton.Tap += new EventHandler<GestureEventArgs>(removeButton_Tap);
                    removeButton.Tag = container;
                    removebuttons.Add(removeButton);
                    disabledremovebuttons.Add(removeButton);

                    TextBlock maxQuantityText = new TextBlock();
                    maxQuantityText.Text = quantity;
                    maxQuantityText.Visibility = System.Windows.Visibility.Collapsed;
                    
                    container.Children.Add(bord);
                    container.Children.Add(nameText);
                    container.Children.Add(topText);
                    container.Children.Add(bottomText);
                    container.Children.Add(leftText);
                    container.Children.Add(rightText);
                    container.Children.Add(quantityText);
                    container.Children.Add(addButton);
                    container.Children.Add(removeButton);
                    container.Children.Add(maxQuantityText);

                    ContainerList.Items.Add(container);
                }
            }
        }

        //Get5Cards

        private void GetRequestStreamCallbackGet5Cards(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&idC1=" + idlist[0] + "&idC2=" + idlist[1] +
                "&idC3=" + idlist[2] + "&idC4=" + idlist[3] + "&idC5=" + idlist[4];
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackGet5Cards), myRequest);
        }//GetRequestStreamCallbackGet5Cards

        private void GetResponsetStreamCallbackGet5Cards(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingGet5Cards(result));
            }
        }//GetResponsetStreamCallbackGet5Cards

        private void ParsingGet5Cards(string result)
        {
            string[] ris = majorSplit(result);

            if (ris[0] == "ERRORE")
            {
                MessageBox.Show(ris[1]);
            }
            else
            {
                int index = 0;
                foreach (string record in ris) //aggiungo le carte al mazzo
                {
                    //id image name top bottom left right rarity level cost
                    string[] dati = minorSplit(record);
                    int id = Convert.ToInt32(dati[0]);
                    string image = dati[1];
                    string name = dati[2];
                    int top = Convert.ToInt32(dati[3]);
                    int bottom = Convert.ToInt32(dati[4]);
                    int left = Convert.ToInt32(dati[5]);
                    int right = Convert.ToInt32(dati[6]);
                    int level = Convert.ToInt32(dati[7]);
                    int cost = Convert.ToInt32(dati[8]);

                    Carta card = new Carta(id, name, image, top, bottom, left, right, cost, level);
                    cardslist[index] = card;
                    index++;
                }
                appSettings.Add("mydeck", new Mazzo(cardslist[0], cardslist[1], cardslist[2], cardslist[3], cardslist[4]));
            }
        }//ParsingGet5Cards
        

        //Search

        private void GetRequestStreamCallbackSearch(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&id=" + io.getId().ToString();
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackSearch), myRequest);
        }//GetRequestStreamCallback

        private void GetResponsetStreamCallbackSearch(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingSearch(result));
            }
        }//GetResponsetStreamCallback

        private void ParsingSearch(string result)
        {
            //controllo result
            if (result != "")//ho trovato qualcuno in cerca di avversario
            {
                //parsing e creo lista
                string[] ris = majorSplit(result);
                var random = new Random();
                int rand = random.Next(0, ris.Count() - 1);
                string[] dati = minorSplit(ris[rand]);

                player2id = Convert.ToInt32(dati[0]);
                player2name = dati[1];

                //nuova partita nel database
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/newMatch.php");
                    HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                    loginRequest.Method = "POST";
                    loginRequest.ContentType = "application/x-www-form-urlencoded";
                    loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackNewMatch), loginRequest);
                }
                else
                {
                    MessageBox.Show("Connection error, please retry later.");
                }
               
            }
            else //mi metto in cerca di avversario
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/lookingForMatch.php");
                    HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                    loginRequest.Method = "POST";
                    loginRequest.ContentType = "application/x-www-form-urlencoded";
                    loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackLookingForMatch), loginRequest);
                }
                else
                {
                    MessageBox.Show("Connection error, please retry later.");
                }
            }
        }

        //New Match

        private void GetRequestStreamCallbackNewMatch(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&IdU1=" + io.getId().ToString() + "&IdU2=" + player2id.ToString();
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackNewMatch), myRequest);
        }//GetRequestStreamCallbackNewMatch

        private void GetResponsetStreamCallbackNewMatch(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingNewMatch(result));
            }
        }//GetResponsetStreamCallbackNewMatch

        private void ParsingNewMatch(string result)
        {
            string[] ris = majorSplit(result);
            ris = minorSplit(ris[0]);//sono sicuro che rappresenta un solo record

            if (ris[0] == "ERRORE")
            {
                //se c'è già una partita col mio id la devo eliminare
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/deleteMatchWithPlayerId.php");
                    HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                    loginRequest.Method = "POST";
                    loginRequest.ContentType = "application/x-www-form-urlencoded";
                    loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackDeleteMatchWithPlayerId), loginRequest);
                }
                else
                {
                    MessageBox.Show("Connection error, please retry later.");
                }
            }
            else
            {
                Utente io = appSettings[key] as Utente;
                appSettings.Add("matchId", result);
                appSettings.Add("turn", io.getId());
                appSettings.Add("idplayer2", player2id);
                appSettings.Add("nameplayer2", player2name);
                popup.IsOpen = false;
                NavigationService.Navigate(new Uri("/Partita.xaml", UriKind.Relative));
            }
            
        }//ParsingNewMatch

        //LookingìForMatch

        private void GetRequestStreamCallbackLookingForMatch(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&ID=" + io.getId().ToString();
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackLookingForMatch), myRequest);
        }//GetRequestStreamCallbackLookingForMatch

        private void GetResponsetStreamCallbackLookingForMatch(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingLookingForMatch(result));
            }
        }//GetResponsetStreamCallbackLookingForMatch

        private void ParsingLookingForMatch(string result)
        {
            string[] ris = majorSplit(result);
            ris = minorSplit(ris[0]);//sono sicuro che rappresenta un solo record

            if (ris[0] == "ERRORE")
            {
                MessageBox.Show(ris[1]);
            }
            else
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/getMatchWithPlayerId.php");
                    HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                    loginRequest.Method = "POST";
                    loginRequest.ContentType = "application/x-www-form-urlencoded";
                    loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackGetMatchWithPlayerId), loginRequest);
                }
                else
                {
                    MessageBox.Show("Connection error, please retry later.");
                }
            }
        }//ParsingLookingForMatch

        //GetMatchWithPlayerId

        private void GetRequestStreamCallbackGetMatchWithPlayerId(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&id=" + io.getId().ToString();
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackGetMatchWithPlayerId), myRequest);
        }//GetRequestStreamCallbackGetMatchWithPlayerId

        private void GetResponsetStreamCallbackGetMatchWithPlayerId(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingGetMatchWithPlayerId(result));
            }
        }//GetResponsetStreamCallbackGetMatchWithPlayerId

        private void ParsingGetMatchWithPlayerId(string result)
        {
            string[] ris = majorSplit(result);
            ris = minorSplit(ris[0]);//sono sicuro che rappresenta un solo record

            if (ris[0] == "ERRORE")
            {
                MessageBox.Show(ris[1]);
            }
            else if (ris[0] == "") //se non ho trovato una partita cerco ancora
            {
                dispatcherTimer.Start();
            }
            else //partita trovata
            {
                dispatcherTimer.Stop();

                //parsing
                string[] dati = minorSplit(result);
                string matchId = dati[0];
                player2id = Convert.ToInt32(dati[1]);
                player2name = dati[2];

                //mi elimino dalla coda
                Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/leaveQueue.php");
                HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                loginRequest.Method = "POST";
                loginRequest.ContentType = "application/x-www-form-urlencoded";
                loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackLeaveQueue), loginRequest);

                appSettings.Add("matchId", matchId);
                appSettings.Add("turn", player2id);
                appSettings.Add("idplayer2", player2id);
                appSettings.Add("nameplayer2", player2name);
                popup.IsOpen = false;
                NavigationService.Navigate(new Uri("/Partita.xaml", UriKind.Relative));
            }

        }//ParsingGetMatchWithPlayerId

        //LeaveQueue

        private void GetRequestStreamCallbackLeaveQueue(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&id=" + io.getId().ToString();
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackLeaveQueue), myRequest);
        }//GetRequestStreamCallbackLeaveQueue

        private void GetResponsetStreamCallbackLeaveQueue(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingLeaveQueue(result));
            }
        }//GetResponsetStreamCallbackLeaveQueue

        private void ParsingLeaveQueue(string result)
        {
            string[] ris = majorSplit(result);
            ris = minorSplit(ris[0]);//sono sicuro che rappresenta un solo record

            if (ris[0] == "ERRORE")
            {
                MessageBox.Show(ris[1]);
            }

        }//ParsingGetLeaveQueue

        private void GetRequestStreamCallbackDeleteMatchWithPlayerId(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&IdPlayer=" + io.getId().ToString();
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackDeleteMatchWithPlayerId), myRequest);
        }//GetRequestStreamCallbackDeleteMatchWithPlayerId

        private void GetResponsetStreamCallbackDeleteMatchWithPlayerId(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingDeleteMatchWithPlayerId(result));
            }
        }//GetResponsetStreamCallbackDeleteMatchWithPlayerId

        private void ParsingDeleteMatchWithPlayerId(string result)
        {
            string[] ris = majorSplit(result);
            ris = minorSplit(ris[0]);//sono sicuro che rappresenta un solo record

            if (ris[0] == "ERRORE")
            {
                MessageBox.Show(ris[1]);
            }
            else
            {
                //nuova partita nel database
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/newMatch.php");
                    HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                    loginRequest.Method = "POST";
                    loginRequest.ContentType = "application/x-www-form-urlencoded";
                    loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackNewMatch), loginRequest);
                }
                else
                {
                    MessageBox.Show("Connection error, please retry later.");
                }
            }
        }//ParsingLookingForMatch


        //splitta la stringa passata in base a |
        private string[] minorSplit(string result)
        {
            return result.Split('|');
        }

        //splitta la stringa passata in base a §
        private string[] majorSplit(string result)
        {
            return result.Split('§');
        }
    }
}